package com.zhida.jiyangcenter.mian

import android.os.Bundle
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.resColor
import chooongg.base.utils.startActivity
import chooongg.base.utils.tipFail
import chooongg.base.utils.toast
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.WebNoTokenActivity
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.dialog.AssessmentDialog
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.YwpAddressBean
import kotlinx.android.synthetic.main.activity_assessment.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

@TitleBar(false)
@ContentLayout(R.layout.activity_assessment)
class AssessmentActivity : BaseActivity() {
    val adapter = Adapter()
    var pinghezhi = 0
    var qixuzhi = 0
    var qiyuzhi = 0
    var shirezhi = 0
    var tanshizhi = 0
    var tebingzhi = 0
    var xueyuzhi = 0
    var yangxuzhi = 0
    var yinxuzhi = 0
    override fun initConfig(savedInstanceState: Bundle?) {
        recycler_view.layoutManager =
            LinearLayoutManager(context)
        recycler_view.adapter = adapter
        title_bar.title("智能评估").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.operationText("提交") {
            if (adapter.datas.size < data.size) {
                toast("请做完题目再提交结果")
            } else {
                adapter.datas.forEach {
                    when (data[it.key].type) {
                        1 -> {
                            yangxuzhi += it.value + 1
                        }
                        2 -> {
                            yinxuzhi += it.value + 1
                        }
                        3 -> {
                            qixuzhi += it.value + 1
                        }
                        4 -> {
                            tanshizhi += it.value + 1
                        }
                        5 -> {
                            shirezhi += it.value + 1
                        }
                        6 -> {
                            shirezhi += it.value + 1
                        }
                        7 -> {
                            shirezhi += it.value + 1
                        }
                        8 -> {
                            xueyuzhi += it.value + 1
                        }
                        9 -> {
                            tebingzhi += it.value + 1
                        }
                        10 -> {
                            qiyuzhi += it.value + 1
                        }
                        11 -> {
                            pinghezhi += if (data[it.key].is_zheng)
                                it.value + 1
                            else
                                (5 - it.value)
                        }

                    }
                }
                lifecycleScope.request({
                    APIPay.service().health_testIndex(
                        pinghezhi,
                        qixuzhi,
                        qiyuzhi,
                        shirezhi,
                        tanshizhi,
                        tebingzhi,
                        xueyuzhi,
                        yangxuzhi,
                        yinxuzhi
                    )
                }, object : BaseAPI<health_testIndexEntity>() {
                    override fun onSuccess(t: health_testIndexEntity?, state: Int, msg: String) {
                        startActivity<WebNoTokenActivity> {
                            putExtra(WebNoTokenActivity.URL, t?.url.toString())
                            putExtra(WebNoTokenActivity.TITLE, "智能评估")
                        }
                        finish()
                    }

                    override fun onError(e: APIException) {
                        tipFail(e.eMessage)
                    }

                })
            }
        }.getOperationTextView().apply {
            setTextColor(resColor(R.color.white))
        }
        val dialog = AssessmentDialog()
        dialog.setListener {
            initData(it)
            recycler_view.setItemViewCacheSize(data.size)
            dialog.dismiss()
        }
        dialog.show(supportFragmentManager, "AssessmentDialog")
    }

    val data = ArrayList<AssessmentEntityItem>()

    /**
     * 初始化数据
     * 拿assets下的json文件
     */
    private fun initData(int: Int) {
        val jsonSB = StringBuilder()
        try {
            val addressJsonStream = BufferedReader(
                InputStreamReader(
                    context.assets.open("assessment.json")
                )
            )
            var line: String?
            while (addressJsonStream.readLine().also { line = it } != null) {
                jsonSB.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        // 将数据转换为对象
        val data1 = Gson().fromJson(jsonSB.toString(), AssessmentEntity::class.java)
        data1.forEach {
            if (int == 0 && it.type != 7) {
                data.add(it)
            }
            if (int == 1 && it.type != 6) {
                data.add(it)
            }
        }
        data.shuffle()
        adapter.setNewData(data)
    }

    class Adapter :
        BaseQuickAdapter<AssessmentEntityItem, BaseViewHolder>(R.layout.item_assessment) {
        var datas = HashMap<Int, Int>()
        override fun convert(helper: BaseViewHolder, item: AssessmentEntityItem) {
            helper.setText(R.id.tv_title, "${(helper.adapterPosition + 1)}、${item.name}")
            val rv_assessment = helper.getView<RecyclerView>(R.id.rv_assessment)
            rv_assessment.layoutManager = GridLayoutManager(mContext, 5)
            rv_assessment.adapter = ItemAdapter().apply {
                setNewData(ArrayList<String>().apply {
                    add("没有")
                    add("很少")
                    add("有时")
                    add("经常")
                    add("总是")
                })
                setOnItemClickListener { _, view, position ->
                    positions = position
                    notifyDataSetChanged()
                    if (!datas.containsKey(helper.adapterPosition)) {
                        datas[helper.adapterPosition] = position
                    } else {
                        datas.remove(helper.adapterPosition)
                        datas[helper.adapterPosition] = position
                    }
                }
            }
        }

        class ItemAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_item_assessment) {
            var positions: Int = -1
            override fun convert(helper: BaseViewHolder, item: String) {
                if (positions == helper.adapterPosition) {
                    helper.getView<TextView>(R.id.text_view).apply {
                        text = item
                        setBackgroundResource(R.drawable.bg_fill_blue100)
                        setTextColor(mContext.resColor(R.color.white))
                    }
                } else
                    helper.getView<TextView>(R.id.text_view).apply {
                        text = item
                        setBackgroundResource(
                            when (helper.adapterPosition) {
                                0 -> {
                                    R.drawable.bg_empty_coloraccent100
                                }
                                1 -> {
                                    R.drawable.bg_empty_f7aa3b100
                                }
                                2 -> {
                                    R.drawable.bg_empty_6399fc100
                                }
                                3 -> {
                                    R.drawable.bg_empty_b17bf4100
                                }
                                else -> {
                                    R.drawable.bg_empty_fc6363100
                                }
                            }
                        )
                        setTextColor(
                            when (helper.adapterPosition) {
                                0 -> {
                                    mContext.resColor(R.color.colorAccent)
                                }
                                1 -> {
                                    mContext.resColor(R.color.f7aa3b)
                                }
                                2 -> {
                                    mContext.resColor(R.color.color_6399fc)
                                }
                                3 -> {
                                    mContext.resColor(R.color.color_b17bf4)
                                }
                                else -> {
                                    mContext.resColor(R.color.color_fc6363)
                                }
                            }
                        )
                    }
            }
        }
    }

}

